/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author checho
 */
import java.net.*;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public class HiloNodo extends Thread{
    
    ServerSocket ss = null;
    Socket conection = null;
    int puerto;
    String archivo;
    
    public HiloNodo (int puerto){
        this.archivo=archivo;
        this.puerto=puerto;
    }
    
    public void enviarArchivo() throws IOException{
        //Read file name to copy        
        System.out.println("Esperando lectura: ");
        DataInputStream in = new DataInputStream(conection.getInputStream());
        String fileName = in.readUTF();
        System.out.println("fileName: "+fileName);
             
        
        // Sendfile                
        File myFile = new File (fileName);
        byte [] mybytearray  = new byte [(int)myFile.length()];
        FileInputStream fis = new FileInputStream(myFile);
        BufferedInputStream bis = new BufferedInputStream(fis);
        bis.read(mybytearray,0,mybytearray.length);
        OutputStream os = conection.getOutputStream();
        System.out.println("Sending...");
        os.write(mybytearray,0,mybytearray.length);
        os.flush();
        conection.close();
    }
    
    @Override
    public void run(){ 
        ServerSocket servsock = null;
        try {
            servsock = new ServerSocket(puerto);
            while(true){
                System.out.println("Esperando conexion...");
            conection = servsock.accept();
            //System.out.println("Accepted connection : " + conection);
             
            enviarArchivo();
            System.out.println("Transferencia Completa");
                            
            }            
        }        
        catch (IOException ex) {
            Logger.getLogger(NodoImpl.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
}
